Laravel 文件上传
文件上传是在项目开发中较为常用的一项功能,通常在用户界面中运用在了头像图片或者说在表单提交中的文件上传等相关场景,在本文中将会以Laravel为例。
hasFile (表单是否存在文件) Laravel为我们提供了hasFile方法来用于检索表单中是否存在文件,在本文中,如果表单包含了文件则返回yes,否则将会返回no,需要配合前端、路由、控制器进行:
1 2 3 4 5 6 7 8 9 10 11 12 <html> <head> <title>This is be Input up</title> </head> <body> <form action="/user/name" method="post" enctype="multipart/form-data" > {{csrf_field ()}} <input type="file" name="images" > <button type="submit" >up file</button> </form> </body> </html>
TestController 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?php namespace App \Http \Controllers ;use http \Cookie ;use Illuminate \Http \Request ;class TestController extends Controller { public function store (Request $request ) { if ($request ->hasFile ('images' )) { echo "yes" ; } else { echo "no" ; } } }
web.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?php Route ::get ('/' , function () { return view ('welcome' ); }); Route ::get ('/input' ,function () { return view ('input' ); }); Route ::post ('/user/name' , array ('uses' =>'TestController@store' ));Route ::get ('/user/name' , 'TestController@store' );
store Laravel还为开发者提供了一种存储上传文件的方法为store,主要存储在/srv/www/htdocs/test_webapp/public/storage目录下,此目录默认情况下是不存在的,所以我们需要使用以下命令进行创建:
php artisan storage:link
TestController 1 2 3 4 5 6 7 8 9 10 11 12 13 <?php namespace App \Http \Controllers ;use http \Cookie ;use Illuminate \Http \Request ;class TestController extends Controller { public function store (Request $request ) { $file = $request ->file ('images' )->store ('public/storage' ); } }
当我们访问“http://localhost:8000/input”的时候,此次我们上传一张图片,之后我们我们会在```/srv/www/htdocs/test_webapp/public/storage```下存储一张我们刚刚上传的照片并经过重命名处理过的:zV193WUEfZSvs00tc78TSu8WPeIbIQjfQnP82ufW.pngw
storeAs storeAs在Laravel项目之中主要用于为上传的文件进行命名,如果你将名称写死那么他将会当你提交第二个文件的时候自动将第一张文件进行替换,当然读者也可以自行进行研究如何让他写活?
TestController 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?php namespace App \Http \Controllers ;use http \Cookie ;use Illuminate \Http \Request ;use Illuminate \Http \Response ;class TestController extends Controller { public function store (Request $request ) { $file = $request ->file ('images' )->storeAs ('public/storage' ,'jiangxue.jpg' ); } }
⬅️ Go back